package com.cyan.app.workflow.activity.SFC;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cyan.app.barcode.CaptureActivity;
import com.cyan.app.workflow.AppContext;
import com.cyan.app.workflow.AppData;
import com.cyan.app.workflow.R;
import com.cyan.app.workflow.base.activity.BaseActivity;
import com.cyan.app.workflow.bean.BaseBean;
import com.cyan.app.workflow.bean.DDPoolListBean;
import com.cyan.app.workflow.bean.CommonBean;
import com.cyan.app.workflow.common.HttpConfig;
import com.cyan.app.workflow.customview.DatePickerDialog;
import com.cyan.app.workflow.util.AppUtils;
import com.cyan.app.workflow.util.network.GetRequestParams;
import com.cyan.app.workflow.widget.PullToRefresh.PullToRefreshBase.OnRefreshListener;
import com.cyan.app.workflow.widget.PullToRefresh.PullToRefreshListView;
import com.cyan.app.workflow.customview.ShowTipDialog;
import com.alibaba.fastjson.annotation.JSONField;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

/**
 * Created by DXW on 2016/12/20.
 * 滴滴物流主页面
 */
public class DDActivity extends BaseActivity implements DDDataFetcher.PoolsObserver {
    public static final String TAG = "DDActivity";
    public static final String MYPOOL_DATAFILE = "sfc_mypool_datafile";
    private TextView mTextView;
    private Button mButton;
    private boolean mShowLoadingDialog;
    private String mFrom;
    private ShowTipDialog mShowTipDialog;
    public static final int REFRESH_VIEW = 1;               //刷新界面
    public static final int REFRESH_DATA = 2;               //静默刷新数据
    public static final int REFRESH_SELECTED = 3;          //选中数据
    public static final int REFRESH_GRAB = 4;               //抢单
    public static final int REFRESH_WASTE = 5;              //作废
    public static final int REFRESH_DELETE = 6;             //删除
    public static final int FILTER_SUB_TYPE_LIVE_WL = 1;  //即时物流tab
    public static final int FILTER_SUB_TYPE_END_WL = 2;   //已完物流tab
    public static final int FILTER_SUB_TYPE_MY_WL = 3;    //我的物流tab
    private LinearLayout mLinLiveWL;
    private LinearLayout mLinEndWL;
    private LinearLayout mLinMyWL;
    private LinearLayout mTitleBar;
    private RelativeLayout mFootLayout;
    public static int mFilterSubType = FILTER_SUB_TYPE_LIVE_WL;
    private long mLastTimeStamp;
    private PullToRefreshListView mPullToRefreshExpandableListView;
    private PullToRefreshListView mPullToRefreshNoDataListView;
    private ListView mPoolShowListView;
    private DDPoolListBean mPoolListOriginObject;
    private DDPoolListBean mPoolListFilterObject;
    private DDPoolListBean mPoolListObject;
    private DDDataAdapter mPoolShowListViewAdapter;
    public static HashMap<String, DDPoolListBean.DDPoolBean> selectedMap = new HashMap<String, DDPoolListBean.DDPoolBean>();
    private View titleView;
    private EditText mEditTextBeginDate;
    private EditText mEditTextEndDate;
    private PopupWindow mPopWindow;
    private EditText mEditTextKw;
    private EditText mEditTextYg;
    private static final String PROSSCODE = "dd_live_pross";
    private EditText mEditTextPross;
    private EditText mEditTextManno;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sfc_dd);
        initDefaultData();
        titleBar();
        initView();
        DDDataFetcher.getInstance().registPoolsObserver(this);
        //第一次加载
        mFilterSubType = FILTER_SUB_TYPE_LIVE_WL;
        mHandler.sendEmptyMessage(REFRESH_DATA);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //MobclickAgent.onPause(this);
        //MobclickAgent.onPageEnd("DDActivity");
    }

    @Override
    protected void onResume() {
        super.onResume();
        //MobclickAgent.onResume(this);
        //MobclickAgent.onPageStart("DDActivity");
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DDDataFetcher.getInstance().unRegistPoolsObserver(this);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void poolsFetchBegin() {
        if (mShowLoadingDialog) {
            mShowTipDialog = new ShowTipDialog();
            mShowTipDialog.showDialog(this);
        }
    }

    @Override
    public void poolsFetchEnd(int resultCode, DDPoolListBean poolList) {
        if (mShowTipDialog != null) {
            mShowTipDialog.closeDialog();
        }
        mShowLoadingDialog = true;
        onRefreshComplete();
        if (resultCode == DDDataFetcher.RESULT_SUCCESS && poolList != null && poolList.getResult().size() > 0) {
            if (mLastTimeStamp == 0) {
                mPoolListOriginObject = poolList;
            } //else {
                //updatePoolListData(mPoolListOriginObject, poolList);
            //}
            mLastTimeStamp = mPoolListOriginObject.getTimeStamp();

            //根据条件进行过滤

            //更新我的物流 表头数量

            //刷新列表
            refreshPoolListView(true);
        } else {
            if (mLastTimeStamp == 0) {
                mPoolListOriginObject = new DDPoolListBean();
                refreshPoolListView(true);
            }
        }
    }

    private void titleBar() {
        mTextView = (TextView) findViewById(R.id.top_title_info);
        mTextView.setText("滴滴物流");
        Button back = (Button) findViewById(R.id.top_title_back);
        back.getBackground().setAlpha(255);// 透明度0~255透明度值 ，值越小越透明
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //返回按钮
                finish();
            }
        });
        mButton = (Button) findViewById(R.id.top_title_refres_with_icon);
        mButton.setVisibility(View.INVISIBLE);
        mButton = (Button) findViewById(R.id.top_title_refres);
        mButton.setVisibility(View.VISIBLE);
        mButton.setText("筛选");
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFilterSubType == FILTER_SUB_TYPE_END_WL) {
                    showFilterDialog();
                } else if (mFilterSubType == FILTER_SUB_TYPE_MY_WL) {
                    showLzDialog();
                }else if (mFilterSubType == FILTER_SUB_TYPE_LIVE_WL) {
                    showLiveFilterDialog();
                }
            }
        });
        titleView = (View) findViewById(R.id.layout_main_ui_top2_title);
    }

    private void initView() {
        mLinLiveWL = (LinearLayout) findViewById(R.id.lin_live_wl);
        mLinEndWL = (LinearLayout) findViewById(R.id.lin_end_wl);
        mLinMyWL = (LinearLayout) findViewById(R.id.lin_my_wl);
        mTitleBar = (LinearLayout) findViewById(R.id.sfd_dd_title);
        mFootLayout = (RelativeLayout) findViewById(R.id.sfc_dd_foot);
        mFootLayout.setVisibility(View.GONE);
        mLinLiveWL.setSelected(true);
        mLinLiveWL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFilterSubType == FILTER_SUB_TYPE_LIVE_WL) return;
                setTitleOnClick(R.id.lin_live_wl);
            }
        });
        mLinEndWL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mFilterSubType == FILTER_SUB_TYPE_END_WL) return;
                if(!AppData.getInstance().isUserLogin()){
                    AppUtils.showTip(DDActivity.this, "请先登录后再操作。");
                    return;
                }
                setTitleOnClick(R.id.lin_end_wl);
            }
        });
        mLinMyWL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!AppData.getInstance().isUserLogin()){
                   AppUtils.showTip(DDActivity.this, "请先登录后再操作。");
                    return;
                }
                if (mFilterSubType == FILTER_SUB_TYPE_MY_WL) return;
                setTitleOnClick(R.id.lin_my_wl);
            }
        });

        mPullToRefreshNoDataListView = (PullToRefreshListView) findViewById(R.id.no_match_show);
        mPullToRefreshNoDataListView.setVisibility(View.GONE);
        mPullToRefreshNoDataListView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessage(REFRESH_DATA);
            }
        });
        ListView listView = mPullToRefreshNoDataListView.getRefreshableView();
        listView.setAdapter(mNoDataAdapter);

        mPullToRefreshExpandableListView = (PullToRefreshListView) findViewById(R.id.match_show_list);
        mPoolShowListView = mPullToRefreshExpandableListView.getRefreshableView();
        mPullToRefreshExpandableListView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mHandler.sendEmptyMessage(REFRESH_DATA);
            }
        });
        mPoolShowListViewAdapter = new DDDataAdapter(this, mHandler, new ArrayList<DDPoolListBean.DDPoolBean>());
        mPoolShowListView.setAdapter(mPoolShowListViewAdapter);
    }

    /**
     * 改变按钮背景
     */
    public void setTitleOnClick(int btnId) {
        mLinLiveWL.setSelected(false);
        mLinEndWL.setSelected(false);
        mLinMyWL.setSelected(false);
        switch (btnId) {
            case R.id.lin_live_wl:
                mFilterSubType = FILTER_SUB_TYPE_LIVE_WL;
                mLinLiveWL.setSelected(true);
                mLastTimeStamp = 0;
                fetchData(FILTER_SUB_TYPE_LIVE_WL, "0");
                break;
            case R.id.lin_end_wl:
                mFilterSubType = FILTER_SUB_TYPE_END_WL;
                mLinEndWL.setSelected(true);
                mPoolListOriginObject = null;
                new FetchEndWLLoader().execute();
                break;
            case R.id.lin_my_wl:
                mFilterSubType = FILTER_SUB_TYPE_MY_WL;
                mLinMyWL.setSelected(true);
                mLastTimeStamp = 0;
                fetchData(FILTER_SUB_TYPE_MY_WL, "0");
                break;
            default:
                mFilterSubType = FILTER_SUB_TYPE_LIVE_WL;
                mLinLiveWL.setSelected(true);
                mLastTimeStamp = 0;
        }
    }

    //没数据处理
    BaseAdapter mNoDataAdapter = new BaseAdapter() {
        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView != null) {
                return convertView;
            }
            convertView = LayoutInflater.from(DDActivity.this).inflate(R.layout.layout_main_nodata, null);
            return convertView;
        }
    };

    //初始值
    private void initDefaultData() {
        mFrom = "";
        mShowLoadingDialog = true;
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REFRESH_VIEW:
                    refreshPoolListView(true);
                    break;
                case REFRESH_DATA:
                    //mShowLoadingDialog = false;
                    fetchData(mFilterSubType, "0");
                    break;
                case REFRESH_GRAB:
                    if(!AppData.getInstance().isUserLogin()){
                        AppUtils.showTip(DDActivity.this, "请先登录后再操作。");
                        return;
                    }
                    new grabLoader().execute(msg.obj.toString(), String.valueOf(REFRESH_GRAB));
                    break;
                case REFRESH_SELECTED:
                    if (msg.arg1 == 1 && !selectedMap.containsKey(msg.obj.toString())) {
                        selectedMap.put(msg.obj.toString(), (DDPoolListBean.DDPoolBean) msg.getData().getSerializable("selectedPool"));
                    } else if (selectedMap.containsKey(msg.obj.toString())) {
                        selectedMap.remove(msg.obj.toString());
                    }
                    break;
                case REFRESH_WASTE:
                    new grabLoader().execute(msg.obj.toString(), String.valueOf(REFRESH_WASTE));
                    break;
                case REFRESH_DELETE:
                    new grabLoader().execute(msg.obj.toString(), String.valueOf(REFRESH_DELETE));
                    break;
                default:
                    break;
            }
        }
    };

    private void onRefreshComplete() {
        if (mPullToRefreshExpandableListView.isRefreshing()) {
            mPullToRefreshExpandableListView.onRefreshComplete();
        }

        if (mPullToRefreshNoDataListView.isRefreshing()) {
            mPullToRefreshNoDataListView.onRefreshComplete();
        }
    }

    //刷新列表
    private void refreshPoolListView(boolean silentRefresh) {
        setTitleView();
        if (mPoolListOriginObject == null) {
            mPullToRefreshNoDataListView.setVisibility(View.VISIBLE);
            mPullToRefreshExpandableListView.setVisibility(View.GONE);
            mNoDataAdapter.notifyDataSetChanged();
            return;
        }

        mPoolListObject = mPoolListOriginObject;
        if (mPoolListObject.getResult().size() == 0) {
            mPullToRefreshNoDataListView.setVisibility(View.VISIBLE);
            mPullToRefreshExpandableListView.setVisibility(View.GONE);
            mNoDataAdapter.notifyDataSetChanged();
            return;
        }
        mPullToRefreshNoDataListView.setVisibility(View.GONE);
        mPullToRefreshExpandableListView.setVisibility(View.VISIBLE);

        mPoolShowListViewAdapter = new DDDataAdapter(this, mHandler, new ArrayList<DDPoolListBean.DDPoolBean>());
        mPoolShowListView.setAdapter(mPoolShowListViewAdapter);
        mPoolShowListViewAdapter.setDatas(mPoolListObject.getResult());
        mPoolShowListViewAdapter.notifyDataSetChanged();

        if(mFilterSubType == FILTER_SUB_TYPE_MY_WL||mFilterSubType==FILTER_SUB_TYPE_END_WL){
            mPullToRefreshNoDataListView.setPullToRefreshEnabled(false);
            mPullToRefreshExpandableListView.setPullToRefreshEnabled(false);
        }
        else {
            mPullToRefreshNoDataListView.setPullToRefreshEnabled(true);
            mPullToRefreshExpandableListView.setPullToRefreshEnabled(true);
        }
    }
    //刷新列表
    private void refreshPoolListView1(boolean silentRefresh,List<DDPoolptListBean.DDPoolptBean> list) {
        setTitleView();
        if (list == null) {
            mPullToRefreshNoDataListView.setVisibility(View.VISIBLE);
            mPullToRefreshExpandableListView.setVisibility(View.GONE);
            mNoDataAdapter.notifyDataSetChanged();
            return;
        }

        if (list.size() == 0) {
            mPullToRefreshNoDataListView.setVisibility(View.VISIBLE);
            mPullToRefreshExpandableListView.setVisibility(View.GONE);
            mNoDataAdapter.notifyDataSetChanged();
            return;
        }
        mPullToRefreshNoDataListView.setVisibility(View.GONE);
        mPullToRefreshExpandableListView.setVisibility(View.VISIBLE);

        EndWlAdapter adapter = new EndWlAdapter();
        mPoolShowListView.setAdapter(adapter);
        adapter.setDatas(list);
        adapter.notifyDataSetChanged();
        if(mFilterSubType == FILTER_SUB_TYPE_MY_WL||mFilterSubType==FILTER_SUB_TYPE_END_WL){
            mPullToRefreshNoDataListView.setPullToRefreshEnabled(false);
            mPullToRefreshExpandableListView.setPullToRefreshEnabled(false);
        }
        else {
            mPullToRefreshNoDataListView.setPullToRefreshEnabled(true);
            mPullToRefreshExpandableListView.setPullToRefreshEnabled(true);
        }
    }
    private void setTitleView() {
        if (mFilterSubType == FILTER_SUB_TYPE_LIVE_WL) {
            mFootLayout.setVisibility(View.GONE);
            mTitleBar.setVisibility(View.GONE);
            mButton.setText("筛选");
        } else if (mFilterSubType == FILTER_SUB_TYPE_MY_WL && mPoolListObject.getResult().size() > 0) {
            mFootLayout.setVisibility(View.GONE);
            mTitleBar.setVisibility(View.GONE);
            mButton.setText("流转");
        } else if (mFilterSubType == FILTER_SUB_TYPE_END_WL) {
            mFootLayout.setVisibility(View.GONE);
            mTitleBar.setVisibility(View.VISIBLE);
            mButton.setText("筛选");
        }
    }

    //抢单，删除，作废
    private class grabLoader extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            if (mShowLoadingDialog) {
                mShowTipDialog = new ShowTipDialog();
                mShowTipDialog.showDialog(DDActivity.this);
            }
        }
        @Override
        protected String doInBackground(String... params) {
            String result = null;
            String action = "222";
            try {
                if (params[1].equals(String.valueOf(REFRESH_GRAB))) {
                    action = "222";
                } else if (params[1].equals(String.valueOf(REFRESH_WASTE))) {
                    action = "227";
                } else if (params[1].equals(String.valueOf(REFRESH_DELETE))) {
                    action = "228";
                }
                JSONObject param = new JSONObject();
                param.put("userno", AppData.getInstance().getUserId());
                param.put("poolid", params[0]);
                result = GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, action, param.toString(), getApplicationContext());
            } catch (Exception e) {
                AppUtils.showTip(DDActivity.this, "作业异常，" + e.toString());
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            CommonBean resultBean = new Gson().fromJson(s, CommonBean.class);
            if (resultBean != null && resultBean.getCode() == 1) {
                //显示
                for (int i = mPoolListObject.getResult().size() - 1; i >= 0; i--) {
                    DDPoolListBean.DDPoolBean poolBean = mPoolListObject.getResult().get(i);
                    if (poolBean.getPoolId().equals(resultBean.getResult())) {
                        mPoolListObject.getResult().remove(poolBean);
                        if(selectedMap.containsKey(poolBean.getPoolId())) {
                            selectedMap.remove(poolBean.getPoolId());
                        }
                    }
                }
                refreshPoolListView(true);
            }
            if (mShowTipDialog != null) {
                mShowTipDialog.closeDialog();
            }
            mShowLoadingDialog = true;

            if (resultBean.getCode() == 1) {
                AppUtils.showTip(DDActivity.this, resultBean.getMsg());
            } else {
                AppUtils.showTip(DDActivity.this, resultBean.getMsg());
            }
        }
    }

    private void fetchData(int type, String timestamp) {
        HashMap<String,String> map = new HashMap<String,String>();
        if (type == FILTER_SUB_TYPE_MY_WL) {
            DDDataFetcher.getInstance().fetchPoolList(FILTER_SUB_TYPE_MY_WL, AppData.getInstance().getUserId(), timestamp);
        } else if (type == FILTER_SUB_TYPE_LIVE_WL) {
            final String pross = PreferenceManager.getDefaultSharedPreferences(this).getString(PROSSCODE,null);
            if(pross!=null){
                map.put("Prosscode",pross);
            }
            DDDataFetcher.getInstance().fetchPoolList(FILTER_SUB_TYPE_LIVE_WL, map);
        }
    }

    //获取已完物流
    private class FetchEndWLLoader extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            if (mShowLoadingDialog) {
                mShowTipDialog = new ShowTipDialog();
                mShowTipDialog.showDialog(DDActivity.this);
            }
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            try {
                JSONObject param = new JSONObject();
                if (params.length == 0) {
                    param.put("userno", AppData.getInstance().getUserId());
                } else {
                    param.put("userno", AppData.getInstance().getUserId());
                    param.put("beginDate", params[0]);
                    param.put("endDate", params[1]);
                }
                result = GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, "224", param.toString(), getApplicationContext());
            } catch (Exception e) {
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            DDPoolptListBean commonBean = new Gson().fromJson(s, DDPoolptListBean.class);
            if (commonBean != null) {
                //显示
                showEndWlList(commonBean.getResult());
            }
            if (mShowTipDialog != null) {
                mShowTipDialog.closeDialog();
            }
            mShowLoadingDialog = true;
        }
    }

    private void showLiveFilterDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.tqm_filter, null);
        mPopWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        //mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setFocusable(true);
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);
        view.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        mPopWindow.showAsDropDown(titleView);
        mEditTextManno =  (EditText) view.findViewById(R.id.tqm_man_seach_manno);
        //mEditTextManno.setInputType(InputType.TYPE_NULL);
        Button mButtonManno=(Button)view.findViewById(R.id.tqm_man_seach_manno_sm);
        mButtonManno.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DDActivity.this, CaptureActivity.class), 0x0002);
            }
        });
        mEditTextPross = (EditText) view.findViewById(R.id.tqm_man_seach_prosscode);
        final String pross = PreferenceManager.getDefaultSharedPreferences(this).getString(PROSSCODE,null);
        if(pross!=null){
            mEditTextPross.setText(String.valueOf(pross));
        }
        // mEditTextPross.setInputType(InputType.TYPE_NULL);

        Button  mButtonPross = (Button) view.findViewById(R.id.tqm_man_seach_prosscode_sm);
        mButtonPross.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(DDActivity.this, GdlzGx1Activity.class);
                startActivityForResult(intent,0x0003);
            }
        });
        Button mSubmit = (Button) view.findViewById(R.id.tqm_man_seach_submit);
        //查询事件
        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
                if(mEditTextPross.getText().toString().isEmpty() && pross!=null){
                    PreferenceManager.getDefaultSharedPreferences(DDActivity.this).edit().remove(PROSSCODE).commit();
                }
                HashMap<String,String> map = new HashMap<String,String>();
                    String pross = mEditTextPross.getText().toString();
                    if(!pross.isEmpty()){
                        map.put("Prosscode",pross);
                    }
                String manno = mEditTextManno.getText().toString();
                if(!manno.isEmpty()){
                    map.put("Manno",manno);
                }
                    DDDataFetcher.getInstance().fetchPoolList(FILTER_SUB_TYPE_LIVE_WL, map);
            }
        });
    }


    //筛选对话框
    private void showFilterDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.sfc_dd_filter, null);
        mPopWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        //mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setFocusable(true);
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);
        view.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        mPopWindow.showAsDropDown(titleView);

        mEditTextBeginDate = (EditText) view.findViewById(R.id.sfc_dd_seach_date_b);
        mEditTextEndDate = (EditText) view.findViewById(R.id.sfc_dd_seach_date_e);
        Button mSubmit = (Button) view.findViewById(R.id.sfc_dd_seach_submit);
        final Calendar c = Calendar.getInstance();
        c.add(Calendar.DATE, -5);
        mEditTextBeginDate.setText(String.format("%d-%02d-%02d", c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DATE)));
        c.add(Calendar.DATE, 5);
        mEditTextEndDate.setText(String.format("%d-%02d-%02d", c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DATE)));
        mEditTextBeginDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(DDActivity.this, 0, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear, int startDayOfMonth) {
                        String textString = String.format("%d-%02d-%02d", startYear, startMonthOfYear + 1, startDayOfMonth);
                        mEditTextBeginDate.setText(textString);
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), false).show();
            }
        });
        mEditTextEndDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new DatePickerDialog(DDActivity.this, 0, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker startDatePicker, int startYear, int startMonthOfYear, int startDayOfMonth) {
                        String textString = String.format("%d-%02d-%02d", startYear, startMonthOfYear + 1, startDayOfMonth);
                        mEditTextEndDate.setText(textString);
                    }
                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DATE), false).show();
            }
        });

        //查询事件
        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopWindow.dismiss();
                String beginDate = mEditTextBeginDate.getText().toString();
                String endDate = mEditTextEndDate.getText().toString();
                new FetchEndWLLoader().execute(beginDate, endDate);

            }
        });
    }

    //显示已完物流 - 查询条件
    private void showEndWlList(final List<DDPoolptListBean.DDPoolptBean> list) {
        setTitleView();
        if(list!=null) {
            DDPoolptListBean.DDPoolptBean bean = (new DDPoolptListBean()).new DDPoolptBean();
            bean.setDate("汇总");
            for (DDPoolptListBean.DDPoolptBean a : list) {
                bean.setAmount((bean.getAmount() == null ? 0 : bean.getAmount()) + a.getAmount());
                bean.setDistance((bean.getDistance() == null ? 0 : bean.getDistance()) + a.getDistance());
                bean.setOnhand1((bean.getOnhand1() == null ? 0 : bean.getOnhand1()) + a.getOnhand1());
                bean.setTimes(bean.getTimes() + a.getTimes());
            }
            list.add(bean);
        }
        refreshPoolListView1(true,list);
       /* EndWlAdapter adapter = new EndWlAdapter();
        mPoolShowListView.setAdapter(adapter);
        adapter.setDatas(list);
        adapter.notifyDataSetChanged();*/

        mPoolShowListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list.size() == position) {
                    return;
                }
                final String date = list.get(position - 1).getDate();
                Intent intent = new Intent();
                intent.putExtra("userno", AppData.getInstance().getUserId());
                intent.putExtra("date", date);
                intent.setClass(DDActivity.this, DDDataDetail.class);
                startActivity(intent);
            }
        });
    }

    private class EndWlAdapter extends BaseAdapter {
        List<DDPoolptListBean.DDPoolptBean> mpoolptList;
        private LayoutInflater mInflater;

        public EndWlAdapter() {
            mInflater = (LayoutInflater) AppContext.getInstance().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void setDatas(List<DDPoolptListBean.DDPoolptBean> poolptList) {
            if (poolptList != null) {
                mpoolptList = poolptList;
            }
        }

        @Override
        public int getCount() {
            return mpoolptList == null ? 0 : mpoolptList.size();
        }

        @Override
        public Object getItem(int position) {
            return mpoolptList == null ? null : mpoolptList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.sfc_dd_tab2, null);
                viewHolder = new ViewHolder();
                viewHolder.Date = (TextView) convertView.findViewById(R.id.dd_tab2_date);
                viewHolder.Times = (TextView) convertView.findViewById(R.id.dd_tab2_times);
                viewHolder.Onhand1 = (TextView) convertView.findViewById(R.id.dd_tab2_onhand1);
                //viewHolder.Onhand2 = (TextView) convertView.findViewById(R.id.dd_tab2_onhand2);
                viewHolder.Distance = (TextView) convertView.findViewById(R.id.dd_tab2_distance);
                viewHolder.Amount = (TextView) convertView.findViewById(R.id.dd_tab2_amount);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.Date.setText(mpoolptList.get(position).getDate());
            viewHolder.Times.setText(String.valueOf(mpoolptList.get(position).getTimes()));
            double onhand1 = mpoolptList.get(position).getOnhand1();
            viewHolder.Onhand1.setText(String.valueOf((int)onhand1));
            //viewHolder.Onhand2.setText(mpoolptList.get(position).getOnhand2().toString());
            double distance = mpoolptList.get(position).getDistance();
            viewHolder.Distance.setText(String.valueOf((int)distance));
            double amount = mpoolptList.get(position).getAmount();
            viewHolder.Amount.setText(String.valueOf((int)amount));
            return convertView;
        }

        class ViewHolder {
            protected TextView Date;
            protected TextView Times;
            protected TextView Onhand1;
            protected TextView Onhand2;
            protected TextView Distance;
            protected TextView Amount;
        }
    }

    private class DDPoolptListBean extends BaseBean{
        @JSONField(name = "DDPools")
        List<DDPoolptBean> Result;

        @JSONField(name = "TimeStamp")
        private long timeStamp;

        public DDPoolptListBean() {
            Result = new ArrayList<DDPoolptBean>();
        }

        public List<DDPoolptBean> getResult() {
            return Result;
        }

        public void setDDPools(List<DDPoolptBean> ddPools) {
            this.Result = ddPools;
        }

        public long getTimeStamp() {
            return timeStamp;
        }

        public void setTimeStamp(long timeStamp) {
            this.timeStamp = timeStamp;
        }

        public class DDPoolptBean {
            private String Userno;
            private String Date;
            private int Times;
            private Double Onhand1;
            private Double Onhand2;
            private Double Distance;
            private Double Amount;

            public String getUserno() {
                return Userno;
            }

            public void setUserno(String userno) {
                Userno = userno;
            }

            public String getDate() {
                return Date;
            }

            public void setDate(String date) {
                Date = date;
            }

            public int getTimes() {
                return Times;
            }

            public void setTimes(int times) {
                Times = times;
            }

            public Double getOnhand1() {
                return Onhand1;
            }

            public void setOnhand1(Double onhand1) {
                Onhand1 = onhand1;
            }

            public Double getOnhand2() {
                return Onhand2;
            }

            public void setOnhand2(Double onhand2) {
                Onhand2 = onhand2;
            }

            public Double getDistance() {
                return Distance;
            }

            public void setDistance(Double distance) {
                Distance = distance;
            }

            public Double getAmount() {
                return Amount;
            }

            public void setAmount(Double amount) {
                Amount = amount;
            }
        }
    }

    //流转对话框
    private void showLzDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.sfc_gdlz_lz, null);
        mPopWindow = new PopupWindow(view, LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        view.setFocusable(true);
        view.setFocusableInTouchMode(true);
        //mPopWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopWindow.setFocusable(true);
        mPopWindow.setTouchable(true);
        mPopWindow.setOutsideTouchable(true);
        view.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mPopWindow.dismiss();
            }
        });
        mPopWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
            }
        });
        mPopWindow.showAsDropDown(titleView);

        mEditTextKw = (EditText) view.findViewById(R.id.sfc_gdlz_lz_kw);
        //mEditTextYg = (EditText) view.findViewById(R.id.sfc_gdlz_lz_ygk);
        Button mButtonKw =(Button)view.findViewById(R.id.sfc_gdlz_lz_kw_sm);
        mButtonKw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DDActivity.this, CaptureActivity.class), 0x0001);
            }
        });
        /*Button mButtonYg =(Button)view.findViewById(R.id.sfc_gdlz_lz_ygk_sm);
        mButtonYg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(DDActivity.this, CaptureActivity.class), 0x0002);
            }
        });*/
        LinearLayout linearLayoutYg = (LinearLayout) view.findViewById(R.id.sfc_gdlz_lz_line_yg);
        linearLayoutYg.setVisibility(View.GONE);
        RelativeLayout top = (RelativeLayout) view.findViewById(R.id.layout_main_ui_top_title);
        top.setVisibility(View.GONE);
        LinearLayout linearLayoutkw = (LinearLayout) view.findViewById(R.id.sfc_gdlz_lz_line_kw);
        //linearLayoutkw.setPadding(0,50,0,50);
        Button mSubmit = (Button) view.findViewById(R.id.sfc_gdlz_lz_submit);
        mSubmit.setTop(50);
        //流转事件
        mSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectedMap.values().size() == 0) {
                    AppUtils.showTip(DDActivity.this, "请选择流转工单");
                } else if (mEditTextKw.getText().toString().isEmpty()) {
                    AppUtils.showTip(DDActivity.this, "库位编号不能为空");
                } else {
                    mPopWindow.dismiss();
                    new lzLoader().execute(AppData.getInstance().getUserId(), mEditTextKw.getText().toString());
                }
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 0x0001 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
            }
            if (!result.contains("10010")) {
                AppUtils.showTip(DDActivity.this, "库位不存在");
            }else{
                mEditTextKw.setText(String.valueOf(result.substring(5)));
            }
        }
        if(requestCode == 0x0002 && resultCode == RESULT_OK) {
            String result = "";
            if(data != null) {
                result = data.getStringExtra("result");
                mEditTextManno.setText(String.valueOf(result));
            }
        }
        if(requestCode == 0x0003 && resultCode == RESULT_OK){
            String result = "";
            if(data != null) {
                result = data.getStringExtra("prosscode");
                mEditTextPross.setText(String.valueOf(result));
                PreferenceManager.getDefaultSharedPreferences(this).edit().putString(PROSSCODE,result).commit();
            }
        }
    }

    //流转作业
    private class lzLoader extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            if (mShowLoadingDialog) {
                mShowTipDialog = new ShowTipDialog();
                mShowTipDialog.showDialog(DDActivity.this);
            }
        }

        @Override
        protected String doInBackground(String... params) {
            String result = null;
            String action = "229";
            try {
                JSONArray array = new JSONArray();
                for (DDPoolListBean.DDPoolBean pool : selectedMap.values()) {
                    JSONObject json = new JSONObject();
                    json.put("PoolId", pool.getPoolId());
                    json.put("Manno", pool.getManno());
                    json.put("Manqty", pool.getOnhand1());
                    json.put("Prosscode", pool.getProssCode());
                    json.put("NextProsscode", pool.getNextPross());
                    json.put("NextProssname", pool.getNextProssName());
                    json.put("Type", pool.getType());
                    array.put(json);
                }
                JSONObject param = new JSONObject();
                param.put("Keyinuserno", params[0]);
                param.put("Wareh", params[1]);
                param.put("Mannoinfo", array);
                result = GetRequestParams.getRequestResult(HttpConfig.HTTP_MAIN_SERVER_URL, action, param.toString(), getApplicationContext());
            } catch (Exception e) {
                AppUtils.showTip(DDActivity.this, "作业异常，" + e.toString());
                Log.e("error", e.toString());
            }
            return result;
        }

        @Override
        protected void onPostExecute(String s) {
            if (s == null) return;
            List<GdlzLzActivity.MannoLzResultBean> mannoLzResultBean = new Gson().fromJson(s, new TypeToken<List<GdlzLzActivity.MannoLzResultBean>>() {
            }.getType());
            String msg = "";
            for (int i = mannoLzResultBean.size() - 1; i >= 0; i--) {
                GdlzLzActivity.MannoLzResultBean lzR = mannoLzResultBean.get(i);
                if (lzR.getCode() == 1) {
                    for (int k = mPoolListObject.getResult().size() - 1; k >= 0; k--) {
                        DDPoolListBean.DDPoolBean p = mPoolListObject.getResult().get(k);
                        if (!p.getPoolId().equals(lzR.getManno())) continue;
                        if (p.getPoolId().equals(lzR.getManno()) && p.getOnhand1() == lzR.getManqty()) {
                            mPoolListObject.getResult().remove(p);
                            selectedMap.remove(p.getPoolId());
                        } else if (p.getPoolId().equals(lzR.getManno()) && p.getOnhand1() > lzR.getManqty()) {
                            mPoolListObject.getResult().get(k).setNextPross("A00");
                            mPoolListObject.getResult().get(k).setNextProssName("待入库");
                            double num = mPoolListObject.getResult().get(k).getOnhand1() - mannoLzResultBean.get(i).getManqty();
                            mPoolListObject.getResult().get(k).setOnhand1(num);
                        }
                    }
                }else {
                    msg = msg + lzR.getManno() + lzR.getMsg() + ",";
                }
            }
            refreshPoolListView(true);
            if (mShowTipDialog != null) {
                mShowTipDialog.closeDialog();
            }
            mShowLoadingDialog = true;
            if (msg == "") {
                AppUtils.showTip(DDActivity.this, "流转成功");
            } else {
                AppUtils.showTip(DDActivity.this, msg);
            }
        }
    }
}
